package com.vert.db.utils;

import com.vert.db.annotations.ID;
import com.vert.db.annotations.Table;
import com.vert.db.annotations.TableField;
import com.vert.db.model.DBModel;


import java.lang.reflect.Field;
import java.util.*;

/**
 * @Classname SqlUtils
 * @Description TODO
 * @Date 2022/5/29 20:16
 * @Created by XiongXiong
 * @Author: X.I.O
 */
public class SqlUtils {

    private static Map<String,Object> tableModelMap = new HashMap<String, Object>();

    public static void build(List<Class<?>> cls){
        if(cls==null){
          return;
        }
        for (int i = 0; i < cls.size(); i++) {
          Class<?> clazz = cls.get(i);
          Table table=clazz.getAnnotation(Table.class);
          if(table == null){
              continue;
          }
          DBModel dbModel=build(clazz);
          tableModelMap.put(clazz.getName(),dbModel);
        }
    }

    /**
     * 获取注解相关信息
     * @return
     */
    public static DBModel build(Class<?> cls){
        Table table=cls.getAnnotation(Table.class);
        if(table==null){
            return null;
        }
        String tableName=table.value();
        //获取属性
        Field[] field=cls.getDeclaredFields();
        String ID="";
        HashMap<String,String> map = new HashMap<String, String>();
        for (int i = 0; i < field.length; i++) {
            Field e = field[i];
            TableField tableField=e.getAnnotation(TableField.class);
            ID id=e.getAnnotation(ID.class);
            if(tableField==null && id == null){
                continue;
            }
            if(tableField!=null){
               String fieldName=e.getName();
                String tableFiledValue=tableField.value();
                map.put(fieldName,tableFiledValue);
            }
            if(id!=null){
                ID=id.value();
                map.put(ID,e.getName());
            }
        }
        DBModel dbModel=new DBModel(tableName,ID,map,cls);
        return dbModel;
    }

    public static DBModel getDBModelByClass(Class< ? > cls){
        if(tableModelMap.get(cls.getName())!=null){
           DBModel dbModel=(DBModel)tableModelMap.get(cls.getName());
           return dbModel;
        }
        return null;
    }





}
